package com.smile.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cronutils.model.field.expression.FieldExpressionFactory.*;
import com.smile.api.*;
import com.smile.commons.Result;
import com.smile.commons.action.ActionUtils;
import com.smile.commons.cron.CronExpressionGenerator;
import com.smile.commons.date.DateTimeUtils;
import com.smile.commons.json.GenericDeserializer;
import com.smile.commons.page.MyBatisPlusPageConverter;
import com.smile.commons.page.R;
import com.smile.commons.request.RequestIdUtils;
import com.smile.mapper.*;
import com.smile.model.domain.*;
import com.smile.model.dto.info.ReturnT;
import com.smile.model.dto.info.XxlJobInfo;
import com.smile.model.dto.info.XxlJobResult;
import com.smile.model.dto.request.*;
import com.smile.model.request.*;
import com.smile.model.response.GetAirportByIdsResponse;
import com.smile.model.response.GetOrganizationByIdsResponse;
import com.smile.model.response.response.GetOnSiteInspectionDetailResponseDTO;
import com.smile.model.response.response.GetOnSiteInspectionListResponseDTO;
import com.smile.model.response.GetAirportByIdResponse;
import com.smile.model.response.GetOrganizationByIdResponse;
import com.smile.request.AddOperateLogRequest;
import com.smile.service.AirlineService;
import com.smile.service.OnSiteInspectionService;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;

import org.dromara.dynamictp.core.executor.DtpExecutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;

import java.time.LocalDate;
import java.time.LocalDateTime;

import java.time.LocalTime;
import java.time.Period;
import java.time.format.TextStyle;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toMap;

@Service
@Slf4j
public class OnSiteInspectionServiceImpl implements OnSiteInspectionService {

    @Autowired
    private OnSiteInspectionMapper onSiteInspectionMapper;

    @Autowired
    private OrganizationApi organizationApi;

    @Autowired
    private InspectionTaskMapper inspectionTaskMapper;

    @Autowired
    private AirportApi airportApi;

    @Autowired
    private FlightTaskApi flightTaskApi;

    @Autowired
    private WayPointMapper wayPointMapper;
    @Autowired
    private AirLineMapper airLineMapper;

    @Autowired
    private OperateLogApi operateLogApi;

    @Autowired
    private AirlineDeviceApi airlineDeviceApi;

    @Autowired
    private DtpExecutor threadPoolExecutor;

    @Autowired
    private AirlineService airlineService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private DtpExecutor dtpExecutor0;

    @Autowired
    private PlanarAirlineMapper planarAirlineMapper;

    @Autowired
    private CoordinatePointMapper coordinatePointMapper;

    @Value("${xxl.job.admin.addresses}")
    private String xxlJobAdminAddresses;
    @Autowired
    private DeviceModelMapper deviceModelMapper;

    @PostConstruct
    public void init() {
        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        RequestContextHolder.setRequestAttributes(sra, true);
    }


    private ScheduledExecutorService service = new ScheduledThreadPoolExecutor(10);

    @Override
    public Page<GetOnSiteInspectionListResponseDTO> getOnSiteInspectionList(GetOnSiteInspectionListRequestDTO getOnSiteInspectionListRequestDTO) throws ExecutionException, InterruptedException {
        QueryWrapper<FeisuanOnSiteInspection> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ObjectUtil.isNotNull(getOnSiteInspectionListRequestDTO) && ObjectUtil.isNotNull(getOnSiteInspectionListRequestDTO.getState()), "state", getOnSiteInspectionListRequestDTO.getState());
        queryWrapper.eq(ObjectUtil.isNotNull(getOnSiteInspectionListRequestDTO) & StrUtil.isNotBlank(getOnSiteInspectionListRequestDTO.getPlanName()), "plan_name", getOnSiteInspectionListRequestDTO.getPlanName());
        queryWrapper.eq("execute_type", 2);
        queryWrapper.orderByDesc("create_time");
        queryWrapper.orderByAsc("id");
        Page<FeisuanOnSiteInspection> page = onSiteInspectionMapper.selectPage(new Page(getOnSiteInspectionListRequestDTO.getCurrentPage(), getOnSiteInspectionListRequestDTO.getPageSize()), queryWrapper);

        Long startTime = System.currentTimeMillis();
        List<Long> collect1 = page.getRecords().stream().map(i -> i.getAirportId()).collect(Collectors.toList());

        if (collect1.isEmpty()) {
            return new Page<GetOnSiteInspectionListResponseDTO>();
        }

        R<Map<Long, GetAirportByIdsResponse>> airportByIds = airportApi.getAirportByIds(collect1);


        List<Long> collect2 = page.getRecords().stream().map(i -> i.getOrganizationId()).collect(Collectors.toList());

        if (collect2.isEmpty()) {
            return new Page<GetOnSiteInspectionListResponseDTO>();
        }

        R<Map<Long, GetOrganizationByIdsResponse>> organizationByIds = organizationApi.getOrganizationByIds(collect2);
        Long endTime = System.currentTimeMillis();

        System.out.println("接口耗时为:" + (endTime - startTime));

        List<Long> collect3 = page.getRecords().stream().map(i -> i.getAirlineId()).collect(Collectors.toList());
        List<FeisuanAirline> feisuanAirlines = airLineMapper.selectBatchIds(collect3);
        Map<Long, FeisuanAirline> collect4 = feisuanAirlines.stream().collect(toMap(FeisuanAirline::getId, Function.identity(), (u1, u2) -> u1));


        Future<List<GetOnSiteInspectionListResponseDTO>> submit = threadPoolExecutor.submit(new Callable<List<GetOnSiteInspectionListResponseDTO>>() {
            @Override
            public List<GetOnSiteInspectionListResponseDTO> call() throws Exception {
                return page.getRecords().stream().map(i -> {
                    GetOnSiteInspectionListResponseDTO getOnSiteInspectionListResponseDTO = BeanUtil.copyProperties(i, GetOnSiteInspectionListResponseDTO.class);

                    if (CollectionUtil.isNotEmpty(collect4) && ObjectUtil.isNotNull(collect4.get(i.getAirlineId()))) {
                        FeisuanAirline feisuanAirline = collect4.get(i.getAirlineId());
                        getOnSiteInspectionListResponseDTO.setAirlineName(feisuanAirline.getAirlineName());

                        if (i.getExecuteType() == null) {
                            System.out.println("executeType为null");
                            System.out.println("id=" + i.getId());
                        }

                        switch (i.getExecuteType()) {
                            case 0:
                                getOnSiteInspectionListResponseDTO.setExecuteType("立即执行");
                                break;
                            case 1:
                                getOnSiteInspectionListResponseDTO.setExecuteType("单次执行");
                                break;
                            case 2:
                                getOnSiteInspectionListResponseDTO.setExecuteType("重复执行");
                                break;
                        }

                        if (i.getExecuteType() == 2) {
                            //0. 指定某个星期几 1. 指定某个月多少号 2 隔多少天执行一次
                            if (i.getJobType() == 0) {
                                String[] week = {"星期天", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
                                getOnSiteInspectionListResponseDTO.setTaskRule("每隔" + i.getWeeks() + "个星期的" + week[i.getWeek()] + "执行");
                            } else if (i.getJobType() == 1) {
                                getOnSiteInspectionListResponseDTO.setTaskRule("每隔" + i.getMonths() + "个月的第" + i.getDay() + "天执行");
                            } else if (i.getJobType() == 2) {
                                getOnSiteInspectionListResponseDTO.setTaskRule("每隔" + i.getDays() + "天执行");
                            }
                        } else {
                            getOnSiteInspectionListResponseDTO.setTaskRule("-");
                        }


                        if (ObjectUtil.isNotNull(airportByIds) && ObjectUtil.isNotNull(airportByIds.getData())
                                && ObjectUtil.isNotNull(airportByIds.getData().get(i.getAirportId()))) {
                            getOnSiteInspectionListResponseDTO.setAirportName(airportByIds.getData().get(i.getAirportId()).getAirportName());
                            getOnSiteInspectionListResponseDTO.setTaskExecuteFeisouOrDrone(airportByIds.getData().get(i.getAirportId()).getAirportName());
                        }

                        if (ObjectUtil.isNotNull(organizationByIds) && ObjectUtil.isNotNull(organizationByIds.getData()) &&
                                ObjectUtil.isNotNull(organizationByIds.getData().get(i.getOrganizationId()))) {
                            getOnSiteInspectionListResponseDTO.setOrganizationName(organizationByIds.getData().get(i.getOrganizationId()).getOrganizationName());
                        } else {
                            getOnSiteInspectionListResponseDTO.setOrganizationName("飞算科技");
                        }
                        return getOnSiteInspectionListResponseDTO;
                    } else {
                        return getOnSiteInspectionListResponseDTO;
                    }


                }).collect(Collectors.toList());
            }
        });


        List<GetOnSiteInspectionListResponseDTO> collect = submit.get();

        Page<GetOnSiteInspectionListResponseDTO> getOnSiteInspectionListResponseDTOPage = MyBatisPlusPageConverter.convertPage(page, GetOnSiteInspectionListResponseDTO.class);
        getOnSiteInspectionListResponseDTOPage.setRecords(collect);


        return getOnSiteInspectionListResponseDTOPage;
    }

    @Override
    public void onSiteInspectionService(AddOnSiteInspectionRequestDTO addOnSiteInspectionRequestDTO) throws Exception {

//        log.info("执行添加巡警计划操作操作,操作用户id为{},requestId={},addOnSiteInspectionRequestDTO={}",
//                StpUtil.getLoginId(), RequestIdUtils.get(), addOnSiteInspectionRequestDTO);

        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        final String[] validDays = {"SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"};


        final String[] jobId = {""};
        //立即执行
        if (addOnSiteInspectionRequestDTO.getExecuteType() == 0 || addOnSiteInspectionRequestDTO.getExecuteType() == 1) {
            Integer executeType = addOnSiteInspectionRequestDTO.getExecuteType();
            RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
            jobId[0] = "1";
            String flightId = UUID.randomUUID().toString();

            FeisuanInspectionTask feisuanInspectionTask = BeanUtil.copyProperties(addOnSiteInspectionRequestDTO, FeisuanInspectionTask.class);

            QueryWrapper<FeisuanWayPoint> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("airline_id", addOnSiteInspectionRequestDTO.getAirlineId());
            Long waypoint = wayPointMapper.selectCount(queryWrapper);
            feisuanInspectionTask.setPlanName(addOnSiteInspectionRequestDTO.getPlanName());
            feisuanInspectionTask.setStatus(1);
            FeisuanAirline feisuanAirlineOld = airLineMapper.selectById(feisuanInspectionTask.getAirlineId());
            if (ObjectUtil.isNull(feisuanAirlineOld)) {
                throw new RuntimeException("航线已删除");
            }
            Long newAirlineId = airlineService.copyAirline(addOnSiteInspectionRequestDTO.getAirlineId());
            System.out.println("航线副本:"+newAirlineId);
            FeisuanAirline feisuanAirline = airLineMapper.selectById(newAirlineId);
            feisuanInspectionTask.setAirportId(addOnSiteInspectionRequestDTO.getAirportId());
            feisuanInspectionTask.setOrganizationId(addOnSiteInspectionRequestDTO.getOrganizationId());
            feisuanInspectionTask.setFlightId(flightId);
            feisuanInspectionTask.setAirlineId(Integer.parseInt(newAirlineId.toString()));
            feisuanInspectionTask.setWaypoint(waypoint.intValue());
            feisuanInspectionTask.setPlanStartTime(LocalDateTime.now());
            feisuanInspectionTask.setAirlineCode(addOnSiteInspectionRequestDTO.getAirlineCode());
            feisuanInspectionTask.setCode(uuid);
            if (executeType == 1) {
                //计划执行时间
                feisuanInspectionTask.setPlanStartTime(addOnSiteInspectionRequestDTO.getSingleDate());
                feisuanInspectionTask.setStartTime(null);
                feisuanInspectionTask.setEndTime(null);
            } else {
                feisuanInspectionTask.setPlanStartTime(LocalDateTime.now());
                feisuanInspectionTask.setStartTime(LocalDateTime.now());
            }
            inspectionTaskMapper.insert(feisuanInspectionTask);


//            Long airlineId = addOnSiteInspectionRequestDTO.getAirlineId();

            if (ObjectUtil.isNotNull(feisuanAirline)) {
                GetAirportByIdRequest getAirportByIdRequest = new GetAirportByIdRequest();
                getAirportByIdRequest.setId(addOnSiteInspectionRequestDTO.getAirportId());
                RequestContextHolder.setRequestAttributes(requestAttributes);
                R<GetAirportByIdResponse> airportById = airportApi.getAirportById(getAirportByIdRequest);
                ExecuteAirlineTaskRequest executeAirlineTaskRequest = new ExecuteAirlineTaskRequest();
                executeAirlineTaskRequest.setAirlineUrl(feisuanAirline.getAirlineUrl());
                executeAirlineTaskRequest.setETag(feisuanAirline.getETag());
                executeAirlineTaskRequest.setFlightId(flightId);

                if (ObjectUtil.isNotNull(airportById) && ObjectUtil.isNotNull(airportById.getData())) {
                    executeAirlineTaskRequest.setGateway(airportById.getData().getGateway());
                } else {
                    throw new RuntimeException("机场不存在");
                }
                try {
                    String bid = UUID.randomUUID().toString();
                    String tid = UUID.randomUUID().toString();
                    executeAirlineTaskRequest.setBid(bid);
                    executeAirlineTaskRequest.setTid(tid);
                    if (executeType == 0) {
                        airlineDeviceApi.executeAirlineTask(executeAirlineTaskRequest);
                    } else {
                        XxlJobInfo xxlJobInfo = new XxlJobInfo();
                        xxlJobInfo.setJobGroup(3);
                        xxlJobInfo.setAuthor("飞算科技");
                        xxlJobInfo.setScheduleType("CRON");
                        xxlJobInfo.setGlueType("BEAN");
                        xxlJobInfo.setExecutorType(1);
                        xxlJobInfo.setScheduleConf(addOnSiteInspectionRequestDTO.getSingleDate().getSecond() + " " + addOnSiteInspectionRequestDTO.getSingleDate().getMinute() + " " + addOnSiteInspectionRequestDTO.getSingleDate().getHour() + " * * ? ");
                        xxlJobInfo.setExecutorHandler("executeInspection");
                        xxlJobInfo.setJobDesc(addOnSiteInspectionRequestDTO.getPlanName());
                        xxlJobInfo.setExecutorRouteStrategy("SHARDING_BROADCAST");
                        xxlJobInfo.setGlueRemark("GLUE代码初始化");
                        xxlJobInfo.setMisfireStrategy("DO_NOTHING");
                        xxlJobInfo.setExecutorBlockStrategy("SERIAL_EXECUTION");
                        xxlJobInfo.setExecutorTimeout(0);
                        xxlJobInfo.setExecutorFailRetryCount(0);
                        xxlJobInfo.setTriggerStatus(1);
                        xxlJobInfo.setExecutorParam(uuid);
                        String json = HttpUtil.post(xxlJobAdminAddresses+"/jobinfo/addJob", JSONObject.toJSONString(xxlJobInfo));
                        ReturnT<XxlJobResult> returnT = GenericDeserializer.parseSingleGeneric(json, ReturnT.class, XxlJobResult.class);
//                        jobId[0] = returnT.getContent().getId();
                        feisuanInspectionTask.setJobId(returnT.getContent().getId());
                        inspectionTaskMapper.updateById(feisuanInspectionTask);
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        } else {
            XxlJobInfo xxlJobInfo = new XxlJobInfo();
            xxlJobInfo.setJobGroup(3);
            xxlJobInfo.setAuthor("飞算科技");
            xxlJobInfo.setScheduleType("CRON");
            xxlJobInfo.setGlueType("BEAN");
            xxlJobInfo.setExecutorType(2);

            /**
             * 隔多少天执行一次
             */
            if (addOnSiteInspectionRequestDTO.getJobType() == 2) {


                log.info("执行根据机场id获取机场操作完成,操作用户id为{},requestId={},执行方式为隔多少天执行一次",
                        StpUtil.getLoginId(), RequestIdUtils.get());
                String cronStr = addOnSiteInspectionRequestDTO.getTime().getSecond() + " " + addOnSiteInspectionRequestDTO.getTime().getMinute() + " " + addOnSiteInspectionRequestDTO.getTime().getHour() + " " + LocalDateTime.now().getDayOfMonth() + "/" + addOnSiteInspectionRequestDTO.getDays() + " * ?";
                xxlJobInfo.setScheduleConf(cronStr);
                //某个星期几执行
            } else if (addOnSiteInspectionRequestDTO.getJobType() == 0) {

                String s = CronExpressionGenerator.generateWeeklyInterval(addOnSiteInspectionRequestDTO.getWeeks(), new ArrayList<>(Arrays.asList(validDays[addOnSiteInspectionRequestDTO.getWeek()])),
                        addOnSiteInspectionRequestDTO.getTime().getHour(), addOnSiteInspectionRequestDTO.getTime().getMinute());
                System.out.println(s);
                xxlJobInfo.setScheduleConf(s);
                //某个月多少号执行
            } else if (addOnSiteInspectionRequestDTO.getJobType() == 1) {
                String s = addOnSiteInspectionRequestDTO.getTime().getSecond() + " " + addOnSiteInspectionRequestDTO.getTime().getMinute() + " " + addOnSiteInspectionRequestDTO.getTime().getHour() + " " + addOnSiteInspectionRequestDTO.getDay() + " " + LocalDateTime.now().getMonthValue() + "/" + addOnSiteInspectionRequestDTO.getMonths() + " ?";
                xxlJobInfo.setScheduleConf(s);
            } else {
                xxlJobInfo.setScheduleConf("0/2 * * * * ?");
            }

//            xxlJobInfo.setScheduleConf("? ? " + addOnSiteInspectionRequestDTO.getHour() + " * ? ?");
//            xxlJobInfo.setExecutorHandler("executeOnSiteInspection");
//            xxlJobInfo.setJobDesc(addOnSiteInspectionRequestDTO.getPlanName());
//            xxlJobInfo.setExecutorRouteStrategy("SHARDING_BROADCAST");
//            xxlJobInfo.setGlueRemark("GLUE代码初始化");
//            xxlJobInfo.setMisfireStrategy("DO_NOTHING");
//            xxlJobInfo.setExecutorBlockStrategy("SERIAL_EXECUTION");
//            xxlJobInfo.setExecutorTimeout(0);
//            xxlJobInfo.setExecutorFailRetryCount(0);
//            xxlJobInfo.setTriggerStatus(1);
//            xxlJobInfo.setExecutorParam(uuid);
        }
        if (addOnSiteInspectionRequestDTO.getExecuteType() == 2) {
            FeisuanOnSiteInspection feisuanOnSiteInspection = BeanUtil.copyProperties(addOnSiteInspectionRequestDTO, FeisuanOnSiteInspection.class);
            feisuanOnSiteInspection.setState(1);
            feisuanOnSiteInspection.setCode(uuid);
            feisuanOnSiteInspection.setCreateTime(LocalDateTime.now());
//            feisuanOnSiteInspection.setJobId(Long.valueOf(jobId[0]));
            if (StrUtil.isNotBlank(addOnSiteInspectionRequestDTO.getAirlineCode())) {
                feisuanOnSiteInspection.setAirlineCode(addOnSiteInspectionRequestDTO.getAirlineCode());
            }
            FeisuanAirline feisuanAirlineOld = airLineMapper.selectById(addOnSiteInspectionRequestDTO.getAirlineId());
            if (ObjectUtil.isNull(feisuanAirlineOld)) {
                throw new RuntimeException("航线已删除");
            }
            Long newAirlineId = airlineService.copyAirline(addOnSiteInspectionRequestDTO.getAirlineId());
            System.out.println("巡检计划也生成航线副本:"+newAirlineId);
            feisuanOnSiteInspection.setAirlineId(newAirlineId);
            onSiteInspectionMapper.insert(feisuanOnSiteInspection);
            //巡检计划立即生成
            executeOnSiteInspectionAll();

        }
    }

    @Override
    public GetOnSiteInspectionDetailResponseDTO getOnSiteInspectionDetail(GetOnSiteInspectionDetailRequestDTO getOnSiteInspectionDetailRequestDTO) {
        FeisuanOnSiteInspection feisuanOnSiteInspection = onSiteInspectionMapper.selectById(getOnSiteInspectionDetailRequestDTO.getId());
        GetOnSiteInspectionDetailResponseDTO getOnSiteInspectionDetailResponseDTO = BeanUtil.copyProperties(feisuanOnSiteInspection, GetOnSiteInspectionDetailResponseDTO.class);

        GetOrganizationByIdRequest getOrganizationByIdRequest = new GetOrganizationByIdRequest();
        getOrganizationByIdRequest.setId(feisuanOnSiteInspection.getOrganizationId());
//        getOnSiteInspectionDetailResponseDTO.setOrganizationName(feisuanOnSiteInspection.getOrganizationId());
        R<GetOrganizationByIdResponse> organizationById = organizationApi.getOrganizationById(getOrganizationByIdRequest);
        if (ObjectUtil.isNotNull(organizationById) && ObjectUtil.isNotNull(organizationById.getData())) {
            getOnSiteInspectionDetailResponseDTO.setOrganizationName(organizationById.getData().getOrganizationName());
//                xxlJobInfo.setAuthor(organizationById.getData().getOrganizationName());
        } else {
            getOnSiteInspectionDetailResponseDTO.setOrganizationName("飞算科技");
        }

        GetAirportByIdRequest getAirportByIdRequest = new GetAirportByIdRequest();
        getAirportByIdRequest.setId(feisuanOnSiteInspection.getAirportId());

        R<GetAirportByIdResponse> airportById = airportApi.getAirportById(getAirportByIdRequest);
        if (ObjectUtil.isNotNull(airportById) && ObjectUtil.isNotNull(airportById.getData())) {
            getOnSiteInspectionDetailResponseDTO.setAirportName(airportById.getData().getAirportName());
        }

        FeisuanAirline feisuanAirline = airLineMapper.selectById(feisuanOnSiteInspection.getAirlineId());
        if (ObjectUtil.isNotNull(feisuanAirline)) {
            getOnSiteInspectionDetailResponseDTO.setAirlineName(feisuanAirline.getAirlineName());
            getOnSiteInspectionDetailResponseDTO.setSeriesId(feisuanAirline.getSeriesId());
            getOnSiteInspectionDetailResponseDTO.setModelId(feisuanAirline.getModelId());
            getOnSiteInspectionDetailResponseDTO.setBrandId(feisuanAirline.getBrandId());
            if (feisuanAirline.getModelId() != null) {
                FeisuanDeviceModel feisuanDeviceModel = deviceModelMapper.selectById(feisuanAirline.getModelId());
                getOnSiteInspectionDetailResponseDTO.setModelName(feisuanDeviceModel.getModelName());
            }
        }


        if (feisuanOnSiteInspection.getExecuteType() == 2) {
            //0. 指定某个星期几 1. 指定某个月多少号 2 隔多少天执行一次
            if (feisuanOnSiteInspection.getJobType() == 0) {
                String[] week = {"星期天", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
                getOnSiteInspectionDetailResponseDTO.setTaskRule("每隔" + feisuanOnSiteInspection.getWeeks() + "个星期的" + week[feisuanOnSiteInspection.getWeek()] + "执行");
            } else if (feisuanOnSiteInspection.getJobType() == 1) {
                getOnSiteInspectionDetailResponseDTO.setTaskRule("每隔" + feisuanOnSiteInspection.getMonths() + "个月的第" + feisuanOnSiteInspection.getDay() + "天执行");
            } else if (feisuanOnSiteInspection.getJobType() == 2) {
                getOnSiteInspectionDetailResponseDTO.setTaskRule("每隔" + feisuanOnSiteInspection.getDays() + "天执行");
            }
        } else {
            getOnSiteInspectionDetailResponseDTO.setTaskRule("-");
        }

        return getOnSiteInspectionDetailResponseDTO;
    }

    @XxlJob("executeOnSiteInspection")
    public void executeOnSiteInspection() throws Exception {

        Long startTime = System.nanoTime();
        System.out.println(XxlJobHelper.getJobParam());
        ExecuteOnSiteInspectionRequestDTO executeOnSiteInspectionRequest = new ExecuteOnSiteInspectionRequestDTO();
        executeOnSiteInspectionRequest.setCode(XxlJobHelper.getJobParam());
        executeOnSiteInspection(executeOnSiteInspectionRequest);
//        FlightTaskPrepareRequest flightTaskPrepareRequest = new FlightTaskPrepareRequest();
//        flightTaskPrepareRequest.setTaskId("123");

//        flightTaskApi.prepare(flightTaskPrepareRequest);
        Long endTime = System.nanoTime();

        AddOperateLogRequest addOperateLogRequest = new AddOperateLogRequest();
        addOperateLogRequest.setOperateModule("任务模块");
        addOperateLogRequest.setOperateName("新增巡检任务");
        addOperateLogRequest.setOperateResult(Boolean.TRUE);
//        addOperateLogRequest.setUserId(Long.valueOf(StpUtil.getLoginId().toString()));
        addOperateLogRequest.setUserId(Long.valueOf("0"));
        addOperateLogRequest.setOperateType(1);
        addOperateLogRequest.setIpAddress(ActionUtils.getIpInfo());
        addOperateLogRequest.setExplorer(ActionUtils.getExplorerInfo());
        addOperateLogRequest.setTimes(endTime - startTime);
        operateLogApi.addOperateLogRequest(addOperateLogRequest);
    }


    /**
     * 创建每天的巡检任务生成
     *
     * @throws Exception
     */
    @XxlJob("executeOnSiteInspectionAll")
    public void executeOnSiteInspectionAll() throws Exception {
        QueryWrapper<FeisuanOnSiteInspection> queryWrapper = new QueryWrapper<>();
//        queryWrapper.lambda().eq(FeisuanOnSiteInspection::getJobType, 1);
        queryWrapper.lambda().eq(FeisuanOnSiteInspection::getExecuteType, 2);//重复定时
        queryWrapper.lt("start_time", LocalDateTime.now());
        queryWrapper.gt("end_time", LocalDateTime.now());
        List<FeisuanOnSiteInspection> list = onSiteInspectionMapper.selectList(queryWrapper);
        System.out.println(JSON.toJSONString(list));
        for (FeisuanOnSiteInspection feisuanOnSiteInspection : list) {
            generationTask(feisuanOnSiteInspection);
        }
    }

    //单次生成
    public void generationTask(FeisuanOnSiteInspection feisuanOnSiteInspection) throws Exception {
        //查询当天有没有在今日生成改计划没有的话再检查
        LocalDate today = LocalDate.now(); // 获取当前日期
        LocalDateTime startOfDay = today.atStartOfDay(); // 当天的开始时间（00:00:00）
        LocalDateTime endOfDay = today.atTime(LocalTime.MAX); // 当天的结束时间（23:59:59）
        QueryWrapper<FeisuanInspectionTask> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("on_site_inspection_id", feisuanOnSiteInspection.getId());
        queryWrapper.gt("plan_start_time", startOfDay);
        queryWrapper.lt("plan_start_time", endOfDay);
        queryWrapper.last("limit 1");
        FeisuanInspectionTask feisuanInspectionTask = inspectionTaskMapper.selectOne(queryWrapper);
        if (ObjectUtil.isNotNull(feisuanInspectionTask)) {
            //当天计划已生成 无需处理
            System.out.println(" 无需处理");
            return;
        }
        LocalTime startTime = LocalTime.now();
        if (feisuanOnSiteInspection.getTime().isBefore(startTime)) {
            System.out.println("当前时间已经过去不在处理");
            return;
        }

        if (feisuanOnSiteInspection.getJobType() == 2) { //按天执行
            System.out.println("生成当天的");
            createInspection(feisuanOnSiteInspection);
            //创建当天的任务
        } else if (feisuanOnSiteInspection.getJobType() == 1) {//按月份的某一天
            System.out.println("进入月份处理");
            //判断当前日期是否贵
            System.out.println(today.getDayOfMonth());
            System.out.println(feisuanOnSiteInspection.getDay());
            if (today.getDayOfMonth() == feisuanOnSiteInspection.getDay()) {
                if (feisuanOnSiteInspection.getMonths() == 1) { //只间隔一个月
                    createInspection(feisuanOnSiteInspection);
                } else {
                    QueryWrapper<FeisuanInspectionTask> queryWrapper2 = new QueryWrapper<>();
                    queryWrapper2.eq("on_site_inspection_id", feisuanOnSiteInspection.getId());
                    queryWrapper2.orderByDesc("plan_start_time");
                    queryWrapper.last("limit 1");
                    FeisuanInspectionTask feisuanInspectionTask2 = inspectionTaskMapper.selectOne(queryWrapper2);

                    if (ObjectUtil.isNotNull(feisuanInspectionTask2)) {
                        LocalDate currentDate = LocalDate.now();
                        LocalDate estimatedDate = feisuanInspectionTask2.getPlanStartTime().toLocalDate();
                        // 计算完整月份差（忽略天数差异）
                        long monthsBetween = ChronoUnit.MONTHS.between(
                                estimatedDate.withDayOfMonth(1),
                                currentDate.withDayOfMonth(1)
                        );

                        System.out.println(monthsBetween);
                        System.out.println(feisuanOnSiteInspection.getMonths());
                        if (monthsBetween >= feisuanOnSiteInspection.getMonths()) {
                            createInspection(feisuanOnSiteInspection);
                        }
                    } else {
                        createInspection(feisuanOnSiteInspection);
                    }
                }
            }
        } else if (feisuanOnSiteInspection.getJobType() == 0) {//按周的某一天
            int dayNumber = today.getDayOfWeek().getValue(); // 1=Monday, 7=Sunday
            System.out.println("进入星期处理");
            //先判断星期是否正确
            if (feisuanOnSiteInspection.getWeek() == dayNumber) {
                if (feisuanOnSiteInspection.getWeeks() == 1) {
                    createInspection(feisuanOnSiteInspection);
                } else {
                    //处理时间间隔的问题
                    QueryWrapper<FeisuanInspectionTask> queryWrapper2 = new QueryWrapper<>();
                    queryWrapper2.eq("on_site_inspection_id", feisuanOnSiteInspection.getId());
                    queryWrapper2.orderByDesc("plan_start_time");
                    queryWrapper.last("limit 1");
                    FeisuanInspectionTask feisuanInspectionTask2 = inspectionTaskMapper.selectOne(queryWrapper2);
                    System.out.println("相差天数" + JSON.toJSONString(feisuanInspectionTask2));
                    if (ObjectUtil.isNotNull(feisuanInspectionTask2)) {
                        LocalDate currentDate = LocalDate.now();
                        LocalDate estimatedDate = feisuanInspectionTask2.getPlanStartTime().toLocalDate();
                        long daysBetween = ChronoUnit.DAYS.between(estimatedDate, currentDate);
                        System.out.println(daysBetween);
                        System.out.println(feisuanOnSiteInspection.getWeeks() * 7L);
                        if (daysBetween >= feisuanOnSiteInspection.getWeeks() * 7L) {
                            createInspection(feisuanOnSiteInspection);
                        }
                    } else {
                        createInspection(feisuanOnSiteInspection);
                    }
                }
            }
        }
    }


    public void createInspection(FeisuanOnSiteInspection feisuanOnSiteInspection) throws Exception {
        String flightId = UUID.randomUUID().toString();
        Long airlineId = feisuanOnSiteInspection.getAirlineId();
        FeisuanAirline feisuanAirline = airLineMapper.selectById(airlineId);
        GetAirportByIdRequest getAirportByIdRequest = new GetAirportByIdRequest();
        getAirportByIdRequest.setId(feisuanOnSiteInspection.getAirportId());
        R<GetAirportByIdResponse> airportById = airportApi.getAirportById(getAirportByIdRequest);
        if (ObjectUtil.isNotNull(feisuanAirline) && ObjectUtil.isNotNull(airportById)
                && ObjectUtil.isNotNull(airportById.getData())) {

            ExecuteAirlineTaskRequest executeAirlineTaskRequest = new ExecuteAirlineTaskRequest();
            executeAirlineTaskRequest.setAirlineUrl(feisuanAirline.getAirlineUrl());
            executeAirlineTaskRequest.setETag(feisuanAirline.getETag());
            executeAirlineTaskRequest.setGateway(airportById.getData().getGateway());
            executeAirlineTaskRequest.setOnSiteInspectionId(feisuanOnSiteInspection.getId());
            String bid = UUID.randomUUID().toString();
            String tid = UUID.randomUUID().toString();
            executeAirlineTaskRequest.setBid(bid);
            executeAirlineTaskRequest.setTid(tid);
            executeAirlineTaskRequest.setFlightId(flightId);
            FeisuanInspectionTask feisuanInspectionTask = BeanUtil.copyProperties(feisuanOnSiteInspection, FeisuanInspectionTask.class);



            Long newAirlineId = airlineService.copyAirline(Long.valueOf(feisuanInspectionTask.getAirlineId()));
            System.out.println("航线副本:"+newAirlineId);
//            FeisuanAirline feisuanAirline = airLineMapper.selectById(newAirlineId);
            feisuanInspectionTask.setAirlineId(Integer.parseInt(newAirlineId.toString()));
            feisuanInspectionTask.setPlanName(feisuanOnSiteInspection.getPlanName());
            feisuanInspectionTask.setStatus(1);
            feisuanInspectionTask.setId(null);
            feisuanInspectionTask.setStartTime(null);
            feisuanInspectionTask.setErrorCode(null);
            feisuanInspectionTask.setEndTime(null);
            feisuanInspectionTask.setAirportId(feisuanOnSiteInspection.getAirportId());
            feisuanInspectionTask.setOrganizationId(feisuanOnSiteInspection.getOrganizationId());
            feisuanInspectionTask.setFlightId(flightId);
            feisuanInspectionTask.setBid(bid);
            feisuanInspectionTask.setTid(bid);
            feisuanInspectionTask.setPlanStartTime(LocalDateTime.of(LocalDate.now(), feisuanOnSiteInspection.getTime()));
            feisuanInspectionTask.setAirlineCode(feisuanOnSiteInspection.getAirlineCode());
            feisuanInspectionTask.setOnSiteInspectionId(feisuanOnSiteInspection.getId());
            inspectionTaskMapper.insert(feisuanInspectionTask);

            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            XxlJobInfo xxlJobInfo = new XxlJobInfo();
            xxlJobInfo.setJobGroup(3);
            xxlJobInfo.setAuthor("飞算科技");
            xxlJobInfo.setScheduleType("CRON");
            xxlJobInfo.setGlueType("BEAN");
            xxlJobInfo.setExecutorType(1);
            xxlJobInfo.setScheduleConf(feisuanOnSiteInspection.getTime().getSecond() + " " + feisuanOnSiteInspection.getTime().getMinute() + " " + feisuanOnSiteInspection.getTime().getHour() + " * * ? ");

//                        xxlJobInfo.setExecutorHandler("executeOnSiteInspection");
            xxlJobInfo.setExecutorHandler("executeInspection");
            xxlJobInfo.setJobDesc(feisuanOnSiteInspection.getPlanName());
            xxlJobInfo.setExecutorRouteStrategy("SHARDING_BROADCAST");
            xxlJobInfo.setGlueRemark("GLUE代码初始化");
            xxlJobInfo.setMisfireStrategy("DO_NOTHING");
            xxlJobInfo.setExecutorBlockStrategy("SERIAL_EXECUTION");
            xxlJobInfo.setExecutorTimeout(0);
            xxlJobInfo.setExecutorFailRetryCount(0);
            xxlJobInfo.setTriggerStatus(1);
            xxlJobInfo.setExecutorParam(uuid);
            String json = HttpUtil.post(xxlJobAdminAddresses + "/jobinfo/addJob", JSONObject.toJSONString(xxlJobInfo));
            ReturnT<XxlJobResult> returnT = GenericDeserializer.parseSingleGeneric(json, ReturnT.class, XxlJobResult.class);
            feisuanInspectionTask.setJobId(returnT.getContent().getId());
            inspectionTaskMapper.updateById(feisuanInspectionTask);
        }

    }

    @XxlJob("executeInspection")
    public void executeInspection() throws Exception {

        Long startTime = System.nanoTime();
        System.out.println(XxlJobHelper.getJobParam());
        ExecuteOnSiteInspectionRequestDTO executeOnSiteInspectionRequest = new ExecuteOnSiteInspectionRequestDTO();
        executeOnSiteInspectionRequest.setCode(XxlJobHelper.getJobParam());
        executeInspection(executeOnSiteInspectionRequest);
//        FlightTaskPrepareRequest flightTaskPrepareRequest = new FlightTaskPrepareRequest();
//        flightTaskPrepareRequest.setTaskId("123");

//        flightTaskApi.prepare(flightTaskPrepareRequest);
        Long endTime = System.nanoTime();

        AddOperateLogRequest addOperateLogRequest = new AddOperateLogRequest();
        addOperateLogRequest.setOperateModule("任务模块");
        addOperateLogRequest.setOperateName("新增巡检任务");
        addOperateLogRequest.setOperateResult(Boolean.TRUE);
//        addOperateLogRequest.setUserId(Long.valueOf(StpUtil.getLoginId().toString()));
        addOperateLogRequest.setUserId(Long.valueOf("0"));
        addOperateLogRequest.setOperateType(1);
        addOperateLogRequest.setIpAddress(ActionUtils.getIpInfo());
        addOperateLogRequest.setExplorer(ActionUtils.getExplorerInfo());
        addOperateLogRequest.setTimes(endTime - startTime);
        operateLogApi.addOperateLogRequest(addOperateLogRequest);
    }

    public static void main(String[] args) {
        LocalDate date1 = LocalDate.of(2025, 9, 20); // 第一个日期
        LocalDate date2 = LocalDate.of(2026, 3, 15); // 第二个日期

        // 计算完整月份差（忽略天数差异）
        long monthsBetween = ChronoUnit.MONTHS.between(
                date1.withDayOfMonth(1),
                date2.withDayOfMonth(1)
        );

        // 计算精确月份差（考虑天数差异）
        Period period = Period.between(date1, date2);
        int totalMonths = period.getYears() * 12 + period.getMonths();

        System.out.println("完整月份差: " + monthsBetween + "个月");
        System.out.println("精确月份差: " + totalMonths + "个月 " + period.getDays() + "天");
    }

    //    @Override
    public void executeInspection(ExecuteOnSiteInspectionRequestDTO executeOnSiteInspectionRequestDTO) throws Exception {
        String flightId = UUID.randomUUID().toString();

        QueryWrapper<FeisuanInspectionTask> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code", executeOnSiteInspectionRequestDTO.getCode());
        queryWrapper.eq("status", 1);
        queryWrapper.last("limit 1");
        FeisuanInspectionTask feisuanInspectionTask = inspectionTaskMapper.selectOne(queryWrapper);
        if (ObjectUtil.isNotNull(feisuanInspectionTask)) {


            Long airlineId = Long.valueOf(feisuanInspectionTask.getAirlineId());

            FeisuanAirline feisuanAirline = airLineMapper.selectById(airlineId);
            GetAirportByIdRequest getAirportByIdRequest = new GetAirportByIdRequest();
            getAirportByIdRequest.setId(feisuanInspectionTask.getAirportId());
            R<GetAirportByIdResponse> airportById = airportApi.getAirportById(getAirportByIdRequest);
            if (ObjectUtil.isNotNull(feisuanAirline) && ObjectUtil.isNotNull(airportById)
                    && ObjectUtil.isNotNull(airportById.getData())) {

                ExecuteAirlineTaskRequest executeAirlineTaskRequest = new ExecuteAirlineTaskRequest();
                executeAirlineTaskRequest.setAirlineUrl(feisuanAirline.getAirlineUrl());
                executeAirlineTaskRequest.setETag(feisuanAirline.getETag());
                executeAirlineTaskRequest.setGateway(airportById.getData().getGateway());
                executeAirlineTaskRequest.setOnSiteInspectionId(feisuanInspectionTask.getId());
                String bid = UUID.randomUUID().toString();
                String tid = UUID.randomUUID().toString();
                executeAirlineTaskRequest.setBid(bid);
                executeAirlineTaskRequest.setTid(tid);
                executeAirlineTaskRequest.setFlightId(flightId);

                R<Result> result = airlineDeviceApi.executeAirlineTask(executeAirlineTaskRequest);
                Result result1 = result.getData();
                if (result1.getStatus() == 0) {
                    feisuanInspectionTask.setStatus(5);
                    feisuanInspectionTask.setErrorMessage(result1.getMessage());
                    feisuanInspectionTask.setErrorCode(1);
                    inspectionTaskMapper.updateById(feisuanInspectionTask);
                }
                //执行删除任务
                System.out.println("执行完成删除单次定时");
                HttpUtil.get(xxlJobAdminAddresses + "/jobinfo/remove?id=" + feisuanInspectionTask.getJobId());
            }
        }
    }


    @Override
    public void executeOnSiteInspection(ExecuteOnSiteInspectionRequestDTO executeOnSiteInspectionRequestDTO) throws Exception {
        String flightId = UUID.randomUUID().toString();

        QueryWrapper<FeisuanOnSiteInspection> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code", executeOnSiteInspectionRequestDTO.getCode());
        List<FeisuanOnSiteInspection> feisuanOnSiteInspections = onSiteInspectionMapper.selectList(queryWrapper);
        if (CollectionUtil.isNotEmpty(feisuanOnSiteInspections)) {

            //判断有没有在重复定时的时间范围中
            FeisuanOnSiteInspection feisuanOnSiteInspection = feisuanOnSiteInspections.get(0);
            if (feisuanOnSiteInspection.getExecuteType() == 2) {

                if (feisuanOnSiteInspection.getStartTime() != null
                        && feisuanOnSiteInspection.getEndTime() != null) {
                    if (!DateTimeUtils.isInRangeInclusive(LocalDateTime.now(), feisuanOnSiteInspection.getStartTime(),
                            feisuanOnSiteInspection.getEndTime())) {
                        System.out.println("已经超出执行时间");
                        return;
//                        throw new RuntimeException("不在有效执行时间内");
                    }
                    if (DateTimeUtils.isAfterEndTime(LocalDateTime.now(), feisuanOnSiteInspection.getEndTime())) {
                        HttpUtil.get(xxlJobAdminAddresses + "/jobinfo/remove?id=" + feisuanOnSiteInspection.getJobId());
                        System.out.println("已经超出执行时间");
                        return;
//                        throw new RuntimeException("已过有效执行时间");
                    }
                }
            }

            //判断是不是在单次执行的日期
            if (feisuanOnSiteInspection.getExecuteType() == 1) {
                if (feisuanOnSiteInspection.getSingleDate() != null) {
                    LocalDateTime localDateTime = LocalDateTime.now();
                    if (!(localDateTime.getYear() == feisuanOnSiteInspection.getSingleDate().getYear()
                            && localDateTime.getMonthValue() == feisuanOnSiteInspection.getSingleDate().getMonthValue()
                            && localDateTime.getDayOfMonth() == feisuanOnSiteInspection.getSingleDate().getDayOfMonth()
                    )) {
                        System.out.println("单次执行时间不对，删除任务");
                        HttpUtil.get(xxlJobAdminAddresses + "/jobinfo/remove?id=" + feisuanOnSiteInspection.getJobId());
                        return;
//                        throw new RuntimeException("不在有效执行时间内");
                    }

                }
            }

            Long airlineId = feisuanOnSiteInspection.getAirlineId();
            FeisuanAirline feisuanAirline = airLineMapper.selectById(airlineId);
            GetAirportByIdRequest getAirportByIdRequest = new GetAirportByIdRequest();
            getAirportByIdRequest.setId(feisuanOnSiteInspection.getAirportId());
            R<GetAirportByIdResponse> airportById = airportApi.getAirportById(getAirportByIdRequest);
            if (ObjectUtil.isNotNull(feisuanAirline) && ObjectUtil.isNotNull(airportById)
                    && ObjectUtil.isNotNull(airportById.getData())) {

                ExecuteAirlineTaskRequest executeAirlineTaskRequest = new ExecuteAirlineTaskRequest();
                executeAirlineTaskRequest.setAirlineUrl(feisuanAirline.getAirlineUrl());
                executeAirlineTaskRequest.setETag(feisuanAirline.getETag());
                executeAirlineTaskRequest.setGateway(airportById.getData().getGateway());
                executeAirlineTaskRequest.setOnSiteInspectionId(feisuanOnSiteInspection.getId());
                String bid = UUID.randomUUID().toString();
                String tid = UUID.randomUUID().toString();
                executeAirlineTaskRequest.setBid(bid);
                executeAirlineTaskRequest.setTid(tid);
                executeAirlineTaskRequest.setFlightId(flightId);
                FeisuanInspectionTask feisuanInspectionTask = BeanUtil.copyProperties(feisuanOnSiteInspection, FeisuanInspectionTask.class);
                feisuanInspectionTask.setPlanName(feisuanOnSiteInspection.getPlanName());
                feisuanInspectionTask.setStatus(1);
                feisuanInspectionTask.setId(null);
                feisuanInspectionTask.setStartTime(LocalDateTime.now());
                feisuanInspectionTask.setAirportId(feisuanOnSiteInspection.getAirportId());
                feisuanInspectionTask.setOrganizationId(feisuanOnSiteInspection.getOrganizationId());
                feisuanInspectionTask.setFlightId(flightId);
                feisuanInspectionTask.setBid(bid);
                feisuanInspectionTask.setTid(bid);
                feisuanInspectionTask.setPlanStartTime(LocalDateTime.now());
                feisuanInspectionTask.setAirlineCode(feisuanOnSiteInspection.getAirlineCode());
                feisuanInspectionTask.setOnSiteInspectionId(feisuanOnSiteInspection.getId());
                inspectionTaskMapper.insert(feisuanInspectionTask);

                R<Result> result = airlineDeviceApi.executeAirlineTask(executeAirlineTaskRequest);
                Result result1 = result.getData();
                if (result1.getStatus() == 0) {
                    feisuanInspectionTask.setStatus(0);
                    feisuanInspectionTask.setErrorMessage(result1.getMessage());
                    inspectionTaskMapper.updateById(feisuanInspectionTask);
                }
                //如果是单次任务
                if (feisuanOnSiteInspections.get(0).getExecuteType() == 1) {
                    //执行删除任务
                    System.out.println("执行完成删除单次定时");
                    HttpUtil.get(xxlJobAdminAddresses + "/jobinfo/remove?id=" + feisuanOnSiteInspection.getJobId());
                }
            }
//            feisuanInspectionTask.setAirportId(feisuanOnSiteInspection.get);
        }
    }

    @Override
    public void editOnsiteInspection(EditOnsiteInspectionRequestDTO editOnsiteInspectionRequestDTO) {
        final String[] validDays = {"SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"};

        UpdateWrapper<FeisuanOnSiteInspection> updateWrapper = new UpdateWrapper<>();

        updateWrapper.eq("id", editOnsiteInspectionRequestDTO.getId());
        updateWrapper.set(ObjectUtil.isNotNull(editOnsiteInspectionRequestDTO.getOrganizationId()), "organization_id", editOnsiteInspectionRequestDTO.getOrganizationId());
        updateWrapper.set(StrUtil.isNotBlank(editOnsiteInspectionRequestDTO.getPlanName()), "plan_name", editOnsiteInspectionRequestDTO.getPlanName());
        updateWrapper.set(ObjectUtil.isNotNull(editOnsiteInspectionRequestDTO.getDay()), "day", editOnsiteInspectionRequestDTO.getDay());
        updateWrapper.set(ObjectUtil.isNotNull(editOnsiteInspectionRequestDTO.getMonths()), "months", editOnsiteInspectionRequestDTO.getMonths());
        updateWrapper.set(ObjectUtil.isNotNull(editOnsiteInspectionRequestDTO.getWeek()), "week", editOnsiteInspectionRequestDTO.getWeek());
        updateWrapper.set(ObjectUtil.isNotNull(editOnsiteInspectionRequestDTO.getDays()), "days", editOnsiteInspectionRequestDTO.getDays());
        updateWrapper.set(ObjectUtil.isNotNull(editOnsiteInspectionRequestDTO.getWeeks()), "weeks", editOnsiteInspectionRequestDTO.getWeeks());
        updateWrapper.set(ObjectUtil.isNotNull(editOnsiteInspectionRequestDTO.getStartTime()), "start_time", editOnsiteInspectionRequestDTO.getStartTime());
        //        updateWrapper.set(ObjectUtil.isNotNull(editOnsiteInspectionRequestDTO.getAirlineId()), "airline_id", editOnsiteInspectionRequestDTO.getAirlineId());
        updateWrapper.set(ObjectUtil.isNotNull(editOnsiteInspectionRequestDTO.getEndTime()), "end_time", editOnsiteInspectionRequestDTO.getEndTime());
        updateWrapper.set(ObjectUtil.isNotNull(editOnsiteInspectionRequestDTO.getTime()), "time", editOnsiteInspectionRequestDTO.getTime());
        //jobType
        updateWrapper.set(ObjectUtil.isNotNull(editOnsiteInspectionRequestDTO.getJobType()), "job_type", editOnsiteInspectionRequestDTO.getJobType());
        updateWrapper.set(ObjectUtil.isNotNull(editOnsiteInspectionRequestDTO.getSingleDate()), "single_date", editOnsiteInspectionRequestDTO.getSingleDate());


        try{

            FeisuanAirline feisuanAirline = airLineMapper.selectById(editOnsiteInspectionRequestDTO.getAirlineId());
            if(feisuanAirline == null){
                throw new RuntimeException("航线已删除");
            }
            Long newAirlineId = airlineService.copyAirline(editOnsiteInspectionRequestDTO.getAirlineId());
            System.out.println("巡检计划也生成航线副本:"+newAirlineId);
            updateWrapper.set(ObjectUtil.isNotNull(newAirlineId), "airline_id", newAirlineId);
        }catch (Exception e){

        }


        onSiteInspectionMapper.update(null, updateWrapper);

        FeisuanOnSiteInspection feisuanOnSiteInspection = onSiteInspectionMapper.selectById(editOnsiteInspectionRequestDTO.getId());
        onSiteInspectionMapper.update(null, updateWrapper);
    }

    @Override
    public void delete(Long id) {
        FeisuanOnSiteInspection feisuanOnSiteInspection = onSiteInspectionMapper.selectById(id);
        HttpUtil.get(xxlJobAdminAddresses + "/jobinfo/remove?id=" + feisuanOnSiteInspection.getJobId());

        onSiteInspectionMapper.deleteById(id);

    }

    @Override
    public void deleteOnSiteInspectionByOrganizationId(Long id) {
        QueryWrapper<FeisuanOnSiteInspection> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("organization_id", id);
        List<FeisuanOnSiteInspection> feisuanOnSiteInspections = onSiteInspectionMapper.selectList(queryWrapper);
        if (CollectionUtil.isNotEmpty(feisuanOnSiteInspections)) {
            delete(feisuanOnSiteInspections.get(0).getId());
        }
    }
}
